﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PServiceBus.Core.Interface;
using PServiceBus.Core.Provider;
using PServiceBus.Core.Runtime.Extensions;
using PServiceBus.Core.Runtime.Transports;
using PServiceBus.Gateway.Interfaces.Exceptions;

namespace PServiceBus.Services.Gateway.Runtime {
    public class ESBTransport {
        private ITransport _transport;
        internal ESBTransport(ITransport transport) {
            _transport = transport;
        }
        public void Send<TMessage>(TMessage message) {
            SendMessage(new List<Dictionary<string, object>>() { message.ToDict() });
        }

        public void Send<TMessage>(ICollection<TMessage> messages) {
            SendMessage(messages.Select(message => message.ToDict()).ToList());
        }

        private void SendMessage(List<Dictionary<string, object>> messages) {
            var transformation = TransportProvider.GetTransformation(_transport.Format);
            var response = _transport.Send(transformation.Transform(messages), messages[0]);
            if (!response.Success) throw new ESBException(response.Message);
        }
    }
}
